<?php
/*
 * dao implements
 * include logger,
 * by lane @2010-10-03
*/
class DAOImpl {
    private static $impl; //can not be extends

    protected function __construct($link, $tablepre) {
        $this->wrapper = DAOWrapper::getWrapper($link);
        $this->tablepre = $tablepre;
    }

    function __clone() {
        return self::$impl;
    }

    function __toString() {
        return "DAO implements.";
    }

    public static function getImpl($link, $tablepre) {
        if (empty(self::$impl)) {
            self::$impl = new DAOImpl($link, $tablepre);
        }
        return self::$impl;
    }

    function getUserByName($username)
    {
        $table = $this->tablepre . 'user';
        $fields = '*';
        $condition = "username='{$username}'";
        $order = '';
        $limit = '1';
        return $this->wrapper->select($table, $fields, $condition, $order, $limit);
    }

    function getUserById($uid)
    {
        $table = $this->tablepre . 'user';
        $fields = '*';
        $condition = "uid='{$uid}'";
        $order = '';
        $limit = '1';
        return $this->wrapper->select($table, $fields, $condition, $order, $limit);
    }

    function addUser($arrUser)
    {
        $table = $this->tablepre . 'user';

        $fieldArr = array();
        $valueArr = array();
        foreach ($arrUser as $key => $val) {
            $fieldArr[] = $key;
            $valueArr[] = "'{$val}'";
        }

        $fields = implode(',', $fieldArr);
        $values = implode(',', $valueArr);

        return $this->wrapper->insert($table, $fields, $values);
    }

    function deleteUserByUid($uid)
    {
        $table = $this->tablepre . 'user';
        $condition = "uid='{$uid}'";
        return $this->wrapper->del($table, $condition);
    }

    function getUsers($limit = 10)
    {
        $table = $this->tablepre . 'user';
        $fields = 'uid,username';
        $condition = '';
        $order = '';
        return $this->wrapper->select($table, $fields, $condition, $order, $limit);
    }
   	/**
   	 * 根据用户id获取密码
   	 * @param $userId
   	 */
    function getPasswdById($userId){
    	$table = $this->tablepre . 'user_passwd';
        $fields = 'passwd';
        $condition = "user_id='{$userId}'";
        $order = '';
        $limit = '1'; 
        $rt = $this->wrapper->select($table, $fields, $condition, $order, $limit);
        if($row = mysql_fetch_array($rt)){
        	$passwd = $row['passwd'];
        }
        return $passwd;
    }
    
    /**
     * 增加登录记录
     * @param $userId
     * @param $session
     */
	function saveLoginLog($userId,$session){
    	$table = $this->tablepre . 'login_record';

        $fieldArr = array();
        $valueArr = array();
        
        $fieldArr[] = "user_id";
        $valueArr[] = "'{$userId}'";
        $fieldArr[] = "status_cd";
        $valueArr[] = "'1'";
        $fieldArr[] = "session_id";
        $valueArr[] = "'{$session}'";

        $fields = implode(',', $fieldArr);
        $values = implode(',', $valueArr);

        return $this->wrapper->insert($table, $fields, $values);
    }
    /**
     * 把之前的登录状态更成失效
     * @param $userId
     */
    function deprecatedLoginStatus($userId){
    	$table = $this->tablepre . 'login_record';
		$keyValues = array();
		$keyValues["status_cd"]="2";
		$keyValues["modify_dt"]="now()";
		$condition = "user_id='{$userId}' and status_cd = '1'" ;
        return $this->wrapper->update($table, $keyValues, $condition);
    }
    /**
     * 根据号码获取用户信息
     * @param $phone
     */
    function getUserByPhone($phone){
    	 
        $sql ="select user_id,phone,status_cd,need_confirm  "
    		." from t_user "
    		." where phone='{$phone}' ";
        $rt = $this->wrapper->query($sql); 
        $userObject = array(); 
        if($rt){
	        while($row = mysql_fetch_array($rt)){
	        	$userObject["userId"] = $row['user_id'];
	        	$userObject["phone"] = $row['phone'];
	        	$userObject["statusCd"] = $row['status_cd'];
	        	$userObject["confirm"] = $row['need_confirm'];
	        }
        }
        return $userObject;
    }
    /**
     * 插入一条用户记录
     * @param $phoneNbr
     * @param $needCheck
     */
    function insertUser($phoneNbr,$needCheck=false){
        $table = $this->tablepre . 'user';

        $fieldArr = array();
        $valueArr = array();
        $fieldArr[] = "phone";
        $valueArr[] = "'{$phoneNbr}'";   
        
        $fieldArr[] = "status_cd";
        $valueArr[] = "'1'";
             
        if($needCheck){
	        $fieldArr[] = "need_confirm";
	        $valueArr[] = "'Y'";	        
        }else{
	        $fieldArr[] = "need_confirm";
	        $valueArr[] = "'N'";	
        }
        $fields = implode(',', $fieldArr);
        $values = implode(',', $valueArr);

        $this->wrapper->insert($table, $fields, $values);  
    }
    
     /**
     * 插入一条用户密码记录
     * @param $phoneNbr
     * @param $needCheck
     */
    function insertUserPasswd($userId,$passwd){
        $table = $this->tablepre . 'user_passwd';

        $fieldArr = array();
        $valueArr = array();
        $fieldArr[] = "user_id";
        $valueArr[] = "'{$userId}'"; 
        $fieldArr[] = "passwd";
        $valueArr[] = "'{$passwd}'";         
         
        $fields = implode(',', $fieldArr);
        $values = implode(',', $valueArr);

        $this->wrapper->insert($table, $fields, $values);  
    }
    
    /**
     * 根据用户sessionId获取用户信息
     * @param $sessionId
     */
    function queryUserBySession($sessionId){
    	$sql ="select a.user_id,a.phone,a.status_cd,a.need_confirm "
    		." from t_user a, t_login_record b "
    		." where a.user_id = b.user_id and b.status_cd =1 and b.session_id = '{$sessionId}'";
        $rt = $this->wrapper->query($sql);
        $user = "";
	     if($rt && $row = mysql_fetch_array($rt)){
        	$user["userId"] = $row['user_id'];
        	$user["phone"] = $row['phone'];
        	$user["statusCd"] = $row['status_cd'];
        	$user["confirm"] = $row['need_confirm'];
        	 
        } 
        return $user;
    }
    /**
     * 根据用户id查询用户的位置
     * @param $userId
     */
    function queryLocationByUserId($userId){
    	$sql ="select id,user_id,longitude,latitude,status_cd,modify_dt"
    		." from t_user_2_location  "
    		." where user_id = '{$userId}'";
        $rt = $this->wrapper->query($sql);
        $location = "";
	     if($rt && $row = mysql_fetch_array($rt)){
        	$location["id"] = $row['id'];
        	$location["userId"] = $row['user_id'];
        	$location["lat"] = $row['latitude'];
        	$location["lon"] = $row['longitude'];
        	$location["statusCd"] = $row['status_cd'];
        	$location["modify_dt"] = $row['modify_dt'];
        	 
        }
        return $location;
    }
    
    /**
     * 插入一条用户的地理位置信息,状态1生效
     * @param $userId
     * @param $lat
     * @param $lon
     */
    function saveUserLocation($userId,$lon,$lat){
    	$sql ="insert t_user_2_location(user_id,longitude,latitude,status_cd,modify_dt)"
    		." values('{$userId}','{$lon}','{$lat}',1,now())";
        $this->wrapper->query($sql);
    }
    
 	/**
     * 更新用户的地理位置
     * @param $userId
     * @param $lat
     * @param $lon
     */
    function updateUserLocation($userId,$lon,$lat){
    	$sql ="update t_user_2_location set longitude= '{$lon}',latitude= '{$lat}',status_cd=1,modify_dt = now() "
    		."  where user_id = '{$userId}'";
        $rt = $this->wrapper->query($sql);
    }
    /**
     * 生成请求位置的请求记录
     * @param $requireUserId  发起请求的用户id
     * @param $locatedUserId 被定位的用户id
     * @param $updateUserId 更新用户的id,-1表示系统更新，其他表示用户自己更新
     * @param $statusCd 0，初始状态；1同意；2拒绝；3长时间无反应
     */
    function generateRequireLoactionRecord($requireUserId,$locatedUserId,$updateUserId,$statusCd){
    	$sql = "insert into t_co_location (require_user_id,located_user_id,update_user_id,status_cd)"
    	." values "
    	."($requireUserId,$locatedUserId,$updateUserId,$statusCd)";
        $this->wrapper->query($sql);
    }
    
    /**
     * 更新请求记录
     * @param $updateUserId
     * @param $statusCd
     */
    function updateRequireLoactionRecord($recordId,$updateUserId,$statusCd){
    	$sql = "update t_co_location "
    	." set status_cd = {$statusCd},update_user_id = {$updateUserId}"
    	." where "
    	." id = {$recordId}";
        $this->wrapper->query($sql);
    }
    
    /**
     * 把请求记录保存到历史记录里面
     * @param $recordId 记录id
     */
    function saveRequireLoactionRecord2History($recordId){
    		$sql = "insert into t_co_location_detail (record_id,require_user_id,located_user_id,status_cd,update_user_id,create_dt,modify_dt)"
    	."  select id,require_user_id,located_user_id,status_cd,update_user_id,create_dt,modify_dt "
    	." where id = {$recordId} ";
        $this->wrapper->query($sql);
    }
    
    /**
     * 在插入后，第一次获取最后自动一次增长的 id
     */
    function queryLastInsertId(){
    	$sql = "select LAST_INSERT_ID() id";
    	$rt = $this->wrapper->query($sql);
        
	     if($rt && $row = mysql_fetch_array($rt)){
        	 return $row["id"];
        }
        return -1;
    }
    
 	/**
 	 * 查询定位信息
 	 * @param $condArray
 	 * 数组里面支持的参数是:
 	 * id：记录id
 	 * nbr:流水号，暂时没意义
 	 * requireUserId:发起请求的用户id
 	 * locatedUserId：被定位的用户id
 	 * statusCd：状态
 	 * 至少必须有一个参数
 	 * 
 	 * @return
 	 * 
 	 */
    function queryCoLocation($condArray){
    	
    	$table = $this->tablepre . 'co_location';
    	
		$condition = " 1=1 "; 
        if(!empty($condArray["id"])){
	       $condition .= " and id = '{$condArray["id"]}'";
        } 
        
        if(!empty($condArray["requireUserId"])){
	        $condition .= " and  require_user_id ='{$condArray["requireUserId"]}'";
        }  
        
        if(!empty($condArray["locatedUserId"])){
	        $condition .= " and located_user_id = '{$condArray["locatedUserId"]}'";
        }  
        
        if(isset($condArray["statusCd"])){
	        $condition .= " and status_cd = '{$condArray["statusCd"]}'";
        }  
        if(!empty($condArray["nbr"])){
	         $condition .= " and nbr = '{$condArray["nbr"]}'";
        }   
        $fields = 'id,nbr,require_user_id,located_user_id,update_user_id,status_cd,create_dt';  
        $rt = $this->wrapper->select($table, $fields, $condition);
        $recordArray = array();
        if(empty($rt)){
        	return $recordArray;
        }
        while($row = mysql_fetch_array($rt)){
        	$temp = new CoLocation();
        	$temp->id = $row["id"];
        	$temp->nbr = $row["nbr"];
        	$temp->requireUserId = $row["require_user_id"];
        	$temp->locatedUserId = $row["located_user_id"];
        	$temp->updateUserId = $row["update_user_id"];
        	$temp->statusCd = $row["status_cd"];
        	$temp->createDt = $row["create_dt"];
        	$recordArray[] = $temp;
        }
        return $recordArray;
    }
    /**
     * 查询具体的请求信息，这样可以获取名字
     * @param $condArray
     */
	function queryCoLocationExtr($condArray){
    	
    	$table = ' t_co_location a,t_user b,t_user c ';
    	
		$condition = " a.require_user_id = b.user_id and a.located_user_id = c.user_id "; 
        if(!empty($condArray["id"])){
	       $condition .= " and a.id = '{$condArray["id"]}'";
        } 
        
        if(!empty($condArray["requireUserId"])){
	        $condition .= " and  a.require_user_id ='{$condArray["requireUserId"]}'";
        }  
        
        if(!empty($condArray["locatedUserId"])){
	        $condition .= " and  a.located_user_id = '{$condArray["locatedUserId"]}'";
        }  
        
        if(isset($condArray["statusCd"])){
	        $condition .= " and a.status_cd = '{$condArray["statusCd"]}'";
        }  
        if(!empty($condArray["nbr"])){
	         $condition .= " and a.nbr = '{$condArray["nbr"]}'";
        }   
        $fields = 'a.id,a.nbr,a.require_user_id,b.phone require_phone,a.located_user_id, c.phone located_phone, a.update_user_id,a.status_cd,a.create_dt';  
        $rt = $this->wrapper->select($table, $fields, $condition,'',10);
        $recordArray = array();
        if(empty($rt)){
        	return $recordArray;
        }
        while($row = mysql_fetch_array($rt)){
        	$temp = new stdClass;
        	$temp->id = $row["id"];
        	$temp->nbr = $row["nbr"];
        	$temp->requireUserId = $row["require_user_id"];
        	$temp->locatedUserId = $row["located_user_id"];
        	$temp->requirePhone = $row["require_phone"];
        	$temp->locatedPhone = $row["located_user_id"];
        	$temp->updateUserId = $row["located_phone"];
        	$temp->statusCd = $row["status_cd"];
        	$temp->createDt = $row["create_dt"];
        	$recordArray[] = $temp;
        }
        return $recordArray;
    }
    /**
     * 更新定位请求应答
     * @param $nbr 
     * @param $connArray
     * 更新的参数只支持 status，updateUserId
     */
	function updateCoLocation($id,$newValsArray){
    	$table = $this->tablepre . 'co_location';
		$keyValues = array();
		if(!empty($newValsArray["statusCd"])){
			$keyValues["status_cd"] = $newValsArray["statusCd"];
		}
		if(!empty($newValsArray["requireUserId"])){
			$keyValues["require_user_id"] = $newValsArray["requireUserId"];
		}
		if(!empty($newValsArray["locatedUserId"])){
			$keyValues["located_user_id"] = $newValsArray["locatedUserId"];
		}
		if(!empty($newValsArray["updateUserId"])){
			$keyValues["update_user_id"] = $newValsArray["updateUserId"];
		} 
		$condition = " id= '{$id}' " ;
        return $this->wrapper->update($table, $keyValues, $condition);
    }
    /**
     * 生成授权流水号
     * @param $recordId t_co_location 中对应的id
     * @param $authUserId  授权用户id
     * @param $statusCd 状态1生效；2失效
     */
    function generatePrivilege($recordId,$authUserId,$statusCd){
    	$sql = " insert into t_co_privilege (record_id,auth_user_id,status_cd)"
    	." values ($recordId,$authUserId,$statusCd)";
    	return $this->wrapper->query($sql);
    }
    /**
     * 查询授权信息
     * @param $condArray
     * id
     * recordId
     * statusCd
     */
 	 function queryCoPrivilege($condArray){
    	
    	$table = $this->tablepre . 'co_privilege';
    	
		$condition = " 1=1 "; 
        if(!empty($condArray["id"])){
	       $condition .= " and id = '{$condArray["id"]}'";
        } 
        
        if(!empty($condArray["recordId"])){
	        $condition .= " and  record_id ='{$condArray["recordId"]}'";
        } 
        if(!empty($condArray["statusCd"])){
	        $condition .= " and  status_cd ='{$condArray["statusCd"]}'";
        }  
         
        $fields = 'id,record_id,priv_nbr,auth_user_id,status_cd,create_dt,modify_dt';  
        $rt = $this->wrapper->select($table, $fields, $condition,'',10);
        $recordArray = array();
        if(empty($rt)){
        	return $recordArray;
        }
        while($row = mysql_fetch_array($rt)){
        	$temp = new CoPrivilege();
        	$temp->id = $row["id"];
        	$temp->recordId = $row["record_id"];
        	$temp->privNbr = $row["priv_nbr"];
        	$temp->authUserId = $row["auth_user_id"]; 
        	$temp->statusCd = $row["status_cd"];
        	$temp->createDt = $row["create_dt"];
        	$temp->modifyDt = $row["modify_dt"];
        	$recordArray[] = $temp;
        }
        return $recordArray;
    }
    /**
     * 查询用户的地理位置
     * @param $reqiureUserId
     * @param $privNbr
     */
    function queryUserLocation($reqiureUserId,$privNbr){
    	$sql = "select a.longitude,a.latitude from "
    	." t_co_location c,t_user_2_location a, t_co_privilege b "
    	." where ".
    	" a.user_id = c.located_user_id  "
    	." and  c.id = b.record_id "
    	." and c.require_user_id = {$reqiureUserId} "
    	." and b.id = $privNbr "
    	." and a.status_cd = 1 ";
    	$temp = "";
   		$rt = $this->wrapper->query($sql); 
        if( $rt &&  $row = mysql_fetch_array($rt)){
        	$temp["lon"] = $row["longitude"];
        	$temp["lat"] = $row["latitude"];
        }
        return $temp;
    }
  	/**
     * 插入一条用户默认分享的地理位置信息,类型是1
     * @param $userId
     * @param $lat
     * @param $lon
     */
    function saveDefaultShareLocation($userId,$lon,$lat){
    	$sql ="insert t_share_location(user_id,lon,lat,type_cd,create_dt)"
    		." values('{$userId}','{$lon}','{$lat}',1,now())";
        $this->wrapper->query($sql);
    }
    
 	/**
     * 更新用户分享的地理位置,除了更新经纬度，还更新状态和修改时间
     * @param $userId
     * @param $lat
     * @param $lon
     */
    function updateShareLocation($userId,$lon,$lat){
    	$sql ="update t_share_location set lon= '{$lon}',lat= '{$lat}', status_cd=1,modify_dt = now() ,status_cd = 1 "
    		."  where user_id = '{$userId}'";
        $rt = $this->wrapper->query($sql);
    }
	/**
	 * 获取指定用户的分享的位置,类型是1
	 * @param $userId
	 */
    function getDefaultShareLocation($userId){
    	$sql ="select user_id,lon,lat,create_dt,modify_dt from t_share_location  "
    		."  where user_id = '{$userId}' and type_cd = 1 LIMIT 0 , 1";
        $rt = $this->wrapper->query($sql);
        $temp = '';
    	if( $rt &&  $row = mysql_fetch_array($rt)){
    		$temp = new stdClass;
        	$temp->lon = $row["lon"];
        	$temp->lat = $row["lat"];
        	$temp->userId = $row["user_id"];
        }
        return $temp;
    }
}


class CoLocation{
	public $id;
	public $nbr;
	public $requireUserId;
	public $locatedUserId;
	public $updateUserId;
	public $statusCd;
	public $createDt;
}


class CoPrivilege{
	public $id;
	public $privNbr;
	public $recordId;
	public $authUserId;
	public $statusCd; 
	public $createDt;
	public $modifyDt;
}